package 哈希表;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LC_18四数之和 {
    public static void main(String[] args){
        int[] nums={-2,-1,-1,1,1,2,2};
        int target=0;
        System.out.println(fourSum(nums,target));
    }
    public static List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        List<List<Integer>> res=new ArrayList<>();
        for(int k=0;k<nums.length;k++){
            //剪枝
            if(nums[k]>0 && target>0 && nums[k]>target)
                break;
            //去重
            if(k>0 && nums[k]==nums[k-1])
                continue;
            for(int i=k+1;i<nums.length;i++){
                //剪枝
                int sum=nums[k]+nums[i];
                if(sum>target && sum>0)
                    break;
                //去重
                if(i>k+1 && nums[i]==nums[i-1])//注：i>k+1
                    continue;
                int left=i+1;
                int right=nums.length-1;
                while(left<right){
                    if(sum+nums[left]+nums[right]>target)
                        right--;
                    else if(sum+nums[left]+nums[right]<target)
                        left++;
                    else{
                        res.add(Arrays.asList(nums[k],nums[i],nums[left],nums[right]));
                        while(right>left && nums[left]==nums[left+1])
                            left++;
                        while(right>left && nums[right]==nums[right-1])
                            right--;
                        left++;
                        right--;
                    }
                }
            }
        }
        return res;
    }
}
